"""
和文件相关的类定义
"""

import json

from data_define import Record

# 先定义一个抽象类用来做顶层设计，确定有哪些功能需要实现
class FileReader:
    def reader(self) -> list[Record]:
        """读取文件的数据，读到的每一条数据都转换为Record对象，将他们都封装到list内返回即可"""
        pass

class TextFileReader(FileReader):
    def __init__(self, path):
        self.path = path # 定义成员变量记录文件的路径

    # 复写（实现抽象方法）父类的方法
    def reader(self) -> list[Record]:
        f = open(self.path, "r", encoding="UTF-8")
        lines = f.readlines()
        data_list = []
        for line in lines:
            data = line.strip().split(",") # 消除读取到的每一行数据的 \n, 然后以 , 分割
            record = Record(data[0], data[1], int(data[2]), data[3])
            data_list.append(record)
        f.close()
        return data_list

class JsonFileReader(FileReader):
    def __init__(self, path):
        self.path = path

    def reader(self) -> list[Record]:
        f = open(self.path, "r", encoding="UTF-8")
        lines = f.readlines()
        data_list = []
        for line in lines:
            data = json.loads(line.strip()) # 消除读取到的每一行数据的, 然后加成python的字典
            record = Record(data['date'], data['order_id'], int(data['money']), data['province'])
            data_list.append(record)
        f.close()
        return data_list

if __name__ == '__main__':
    textFileReader = TextFileReader("E:/storage/study/Python/python-learn/day01/02-python-learn/11_面向对象/数据分析案例/素材/2011年1月销售数据.txt")
    for line in textFileReader.reader():
        print(line)

    jsonFileReader = JsonFileReader("E:/storage/study/Python/python-learn/day01/02-python-learn/11_面向对象/数据分析案例/素材/2011年2月销售数据JSON.txt")

    for jsonLine in jsonFileReader.reader():
        print(jsonLine)